#include "StdAfx.h"
#include "PsapiFunc.h"

LPWSTR CPsApiFunc::m_sDllName = L"psapi.dll";

CPsApiFunc::CPsApiFunc()
: m_bInit(FALSE),
m_hMod(NULL)
{
    
}

CPsApiFunc::~CPsApiFunc()
{
    
}

BOOL CPsApiFunc::Initialize()
{
    if (!m_bInit)
    {
        m_hMod = ::LoadLibrary(m_sDllName);
        if (m_hMod)
        {
            m_pFunEnumProcessModules = (PFUN_EnumProcessModules)::GetProcAddress(m_hMod, "EnumProcessModules");
            m_pFunGetModuleFileNameExW = (PFUN_GetModuleFileNameExW)::GetProcAddress(m_hMod, "GetModuleFileNameExW");
            m_pFunGetModuleInformation = (PFUN_GetModuleInformation)::GetProcAddress(m_hMod, "GetModuleInformation");

            if (m_pFunEnumProcessModules && m_pFunGetModuleFileNameExW && m_pFunGetModuleFileNameExW)
            {
                m_bInit = TRUE;
            }
            else
            {
                ::FreeLibrary(m_hMod);
                m_hMod = NULL;
            }
        }
    }

    return m_bInit;
}

VOID CPsApiFunc::UnInitialize()
{
    if (m_bInit && m_hMod)
    {
        ::FreeLibrary(m_hMod);
        m_hMod = NULL;
        m_bInit = FALSE;
    }
}

BOOL CPsApiFunc::FunEnumProcessModules(HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded)
{
    if (m_bInit)
    {
        return (*m_pFunEnumProcessModules)(hProcess, lphModule, cb, lpcbNeeded);
    }

    return m_bInit;
}

DWORD CPsApiFunc::FunGetModuleFileNameExW(HANDLE hProcess, HMODULE hModule, LPWSTR lpFilename, DWORD nSize)
{
    if (m_bInit)
    {
        return (*m_pFunGetModuleFileNameExW)(hProcess, hModule, lpFilename, nSize);
    }
    
    return 0;
}

BOOL CPsApiFunc::FunGetModuleInformation(HANDLE hProcess, HMODULE hModule, LPMODULEINFO lpmodinfo, DWORD cb)
{
    if (m_bInit)
    {
        return (*m_pFunGetModuleInformation)(hProcess, hModule, lpmodinfo, cb);
    }

    return m_bInit;
}